import { onBeforeUnmount, onMounted, ref } from 'vue'

type UseMouseEventCallback = (target?: HTMLElement, isEnter?: boolean) => void

export function useMouseEvent(callback: UseMouseEventCallback) {
  const targetRef = ref<HTMLElement>()

  function handleMouseEnter() {
    if (typeof callback === 'function') {
      callback(targetRef.value as HTMLElement, true)
    }
  }

  function handleMouseLeave() {
    if (typeof callback === 'function') {
      callback(targetRef.value as HTMLElement, false)
    }
  }

  onMounted(() => {
    targetRef.value?.addEventListener('mouseenter', handleMouseEnter)
    targetRef.value?.addEventListener('mouseleave', handleMouseLeave)
  })

  onBeforeUnmount(() => {
    targetRef.value?.removeEventListener('mouseenter', handleMouseEnter)
    targetRef.value?.removeEventListener('mouseleave', handleMouseLeave)
  })

  return {
    targetRef,
  }
}
